<?php
namespace app\api\controller;
use app\common\controller\CommonApi;
use think\Db;
use Pay\Pay;
/**
 * 广告位相关
 */
class Ad extends CommonApi{
    protected $tn = 'common/ad_buy';


    //下单
    public function addOrder(){
        $validate = new \think\validate([
            'foreign_key' => 'require',
            'buy_num' => 'require',
            'title' => 'require',
            'issue_time' => 'require|dateFormat:Y-m-d H:i'
        ],[
            'foreign_key.require' => '请选择广告类型',
            'buy_num.require' => '请选择可见人数',
            'title.require' => '请输入标题',
            'issue_time.require' => '请选择发布时间',
            'issue_time.dateFormat' => '发布时间格式错误'
        ]);
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        if(intval($this->post['buy_num']) <= 0){
            $this->apiReturn(0,'请选择有效的可见人数');
        }

        $issue_time = strtotime($this->post['issue_time']);
        if($issue_time < strtotime(date('Y-m-d H:i'))){
            $this->apiReturn(0,'发布时间不得小于当前时间');
        }

        $res = db('ad_price')->where('id',$this->post['foreign_key'])->find();
        if(is_null($res)){
            $this->apiReturn(0,'广告类型错误');
        }

        $this->post['position_id'] = $res['foreign_key'];
        $this->post['issue_time'] = $issue_time;
        $this->post['price'] = sprintf('%.2f',intval($this->post['buy_num']) * floatval($res['price']));
        $this->post['user_id'] = UID;
        if(!model($this->tn)->allowField(true)->save($this->post)){
            $this->apiReturn(0,'下单失败，请稍后再试');
        }
        $this->apiReturn(1,'下单成功',model($this->tn)->id);
    }   

    //支付
    public function pay(){
        $validate = new \think\validate([
            'id' => 'require',
            'pay_type' => 'require|in:0,1,2'
        ],[
            'id.require' => '参数id丢失',
            'pay_type.require' => '请选择支付方式',
            'pay_type.in' => '支付方式有误'
        ]);
        
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        $model = model($this->tn)->get(intval($this->post['id']));
        if(is_null($model) || $model['user_id'] != UID){
            $this->apiReturn(0,'信息有误');
        }
        if($model['status'] != 0){
            $this->apiReturn(0,'状态错误');
        }
        $order_no = date('YmdHis').rand(10000,99999);
        //余额支付
        if($this->post['pay_type'] == 0){
            if($this->user_info['balance'] < $model['price']){
                $this->apiReturn(0,'账户余额不足');
            }
            db()->startTrans();
            //修改订单状态
            if(!$model->save([
                'status' => 1,
                'order_no' => $order_no,
                'pay_type' => 0,
                'pay_time' => time(),
            ])){
                db()->rollback();
                $this->apiReturn(0,'订单状态修改失败');
            }
            //修改账户余额
            if(!db('user')->where('id',UID)->setDec('balance',$model['price'])){
                db()->rollback();
                $this->apiReturn(0,'账户余额修改失败');
            }

            //添加交易记录
            if(!db('bill')->insert([
                'user_id' => UID,
                'type' => 5,
                'num' => $model['price'],
                'foreign_key' => $model['id'],
                'add_time' => time()
            ])){
                db()->rollback();
                $this->apiReturn(0,'交易记录添加失败');
            }

            if(!db('information')->insert([
                'user_id' => UID,
                'type' => 5,
                'content' => '购买广告位，支付成功',
                'add_time' => time()
            ])){
                db()->rollback();
                $this->apiReturn(0,'信息添加失败');
            }

            if(!model('common/admin_bill')->addBill($this->user_info['from_city'],$model['price'],$model['id'],2)){
                db()->rollback();
                $this->apiReturn(0,'操作失败，未知错误');
            }
            
            db()->commit();
            $this->apiReturn(1,'支付成功');
        }   
        //微信支付
        if($this->post['pay_type'] == 1){
            $options = [
                'out_trade_no' => $order_no,
                'total_fee' => $model['price'] * 100,
                'body' => '购买广告位',
                'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
                'attach' => serialize(['attach' => 3,'id' => $model['id']])
            ];
            $pay = new Pay(config('pay'));

            try{
                $result = $pay->driver('wechat')->gateway('app')->apply($options);
                $this->apiReturn(1,'微信支付信息',$result);
            } catch (Exception $e){
                $this->apiReturn(0,$e->getMessage());

            }
        }
        //支付宝支付
        if($this->post['pay_type'] == 2){
            $options = [
                'out_trade_no' => $order_no,
                'total_amount' =>  $model['price'],
                'subject' => '购买广告位',
                'passback_params' => UrlEncode(serialize(['passback_params' => 3,'id' => $model['id']]))
            ];
            $pay = new Pay(config('pay'));
            try{
                $result = $pay->driver('alipay')->gateway('app')->apply($options);
                $this->apiReturn(1,'支付宝支付信息',$result);
            } catch (Exception $e){
                $this->apiReturn(0,$e->getMessage());

            }
        }
    }
}
